package com.example.administrator.myapplication.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.base.BaseActivity;
import com.example.administrator.myapplication.mode.RecordDataManager;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;

import butterknife.BindView;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

import static com.example.administrator.myapplication.view.HomeActivity.REQUEST_CODE;

/**
 * 说明：根据内容生成二维码
 * 作者： 阳2012; 创建于： 2017/5/12 22:30
 */
public class CreateQRActivity extends BaseActivity {
    public EditText editText = null;
    public ImageView imageView = null;
    public Bitmap mBitmap = null;
    @BindView(R.id.switch1)
    Switch mSwitch;
    @BindView(R.id.floatingActionButton)
    FloatingActionButton mFloatingActionButton;

    boolean isShowLogo = false;

    ArrayList<String> picturePath = new ArrayList<>();
    @BindView(R.id.picture)
    ImageView picture;
    @BindView(R.id.image_content)
    ImageView imageContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        initView();
    }

    @Override
    public int getContentView() {
        return R.layout.activity_three;
    }

    @Override
    public void parseIntent(Intent intent) {

    }

    /**
     * 初始化组件
     */
    @Override
    public void initView() {
        toolbar.setTitle("生成 二维码图片");
        toolbar.setNavigationIcon(R.drawable.material_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        editText = (EditText) findViewById(R.id.edit_content);
        imageView = (ImageView) findViewById(R.id.image_content);


        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isShowLogo = isChecked;
                if (isChecked) {
                    MultiImageSelector.create()
                            .showCamera(true)
                            .single()
                            .origin(picturePath)
                            .start(CreateQRActivity.this, REQUEST_CODE);
                }

            }
        });

        //重新搜索
        mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RecordDataManager.getInstands().save(editText.getText().toString());

                /**
                 * 生成二维码图片
                 */
                if (isShowLogo) {
                    String textContent = editText.getText().toString();
                    if (TextUtils.isEmpty(textContent)) {
                        Toast.makeText(CreateQRActivity.this, "您的输入为空!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    editText.setText("");

                    if (picturePath.size() > 0) {
                        Bitmap logo = resizeBitMapImage1(picturePath.get(0), 200, 200);
                        mBitmap = CodeUtils.createImage(textContent, 500, 500, logo);
                    } else {
                        mBitmap = CodeUtils.createImage(textContent, 400, 400, BitmapFactory.decodeResource(getResources(), R.mipmap.wxxw));
                    }

                    imageView.setImageBitmap(mBitmap);
                    /**
                     * 生成不带logo的二维码图片
                     */
                } else {
                    String textContent = editText.getText().toString();
                    if (TextUtils.isEmpty(textContent)) {
                        Toast.makeText(CreateQRActivity.this, "您的输入为空!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    editText.setText("");
                    mBitmap = CodeUtils.createImage(textContent, 400, 400, null);
                    imageView.setImageBitmap(mBitmap);
                }


            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //过程图片路径
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            picturePath.clear();
            picturePath.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));

            Glide
                    .with(this)
                    .load(picturePath.get(0))
                    .into(picture);

        }
    }


    public static Bitmap resizeBitMapImage1(String filePath, int targetWidth, int targetHeight) {
        Bitmap bitMapImage = null;
        // First, get the dimensions of the image
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        double sampleSize = 0;
        // Only scale if we need to
        // (16384 buffer for img processing)
        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
                .abs(options.outWidth - targetWidth);
        if (options.outHeight * options.outWidth * 2 >= 1638) {
            // Load, scaling to smallest power of 2 that'll get it <= desired
            // dimensions
            sampleSize = scaleByHeight ? options.outHeight / targetHeight
                    : options.outWidth / targetWidth;
            sampleSize = (int) Math.pow(2d,
                    Math.floor(Math.log(sampleSize) / Math.log(2d)));
        }
        // Do the actual decoding
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[128];
        while (true) {
            try {
                options.inSampleSize = (int) sampleSize;
                bitMapImage = BitmapFactory.decodeFile(filePath, options);
                break;
            } catch (Exception ex) {
                try {
                    sampleSize = sampleSize * 2;
                } catch (Exception ex1) {
                }
            }
        }
        return bitMapImage;
    }
}
